package com.spring.sunflower.common;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.ReportPicBean;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.PathUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kevin on 2021/6/24<br/>
 * <p>
 * Describe:<br/>
 */
public class ReportActivity extends BaseActivity<ReportPresenter> implements CommonContract.ReportView {
    private RecyclerView recyclerView;
    private List<ReportPicBean> picList = new ArrayList<>();
    private ReportPhotoAdapter mAdapter;
    private AliUploadUtils aliUploadUtils;
    private StringBuilder pathData = new StringBuilder();
    private List<String> picPathList = new ArrayList<>();
    private EditText etContent;
    private String keyID = "", keySecret = "", securityToken = "";
    private boolean hasAddButton = false;
    private TextView tvContentNum;

    @Override
    public void initView() {
        Intent intent = getIntent();
        String reportType = intent.getStringExtra(Constant.KEY_REPORT_TYPE);
        String reportName = intent.getStringExtra("reportName");
        String otherID = intent.getStringExtra("otherID");
        String userID = getField(Constant.KEY_USERID, "");
        tvTitle.setText(reportName);
        tvFunctionX.setText("提交");
        etContent = findViewById(R.id.etContent);
        tvContentNum = findViewById(R.id.tvContentNum);
        recyclerView = findViewById(R.id.rvRecyclerView);
        mPresenter.getSTSCert();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        mAdapter = new ReportPhotoAdapter(R.layout.adapter_item_photo_list, picList);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                ReportPicBean bean = picList.get(position);
                if (bean.isPlaceholder()) {
                    //上传照片
                    checkOpenGallery(ReportActivity.this,false);
                } else {

                }
            }
        });
        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                List<ReportPicBean> data = new ArrayList<>();
                for (ReportPicBean bean : picList) {
                    bean.setShowDelete(true);
                    data.add(bean);
                }
                mAdapter.setNewInstance(data);
                return true;
            }
        });
        mAdapter.addChildClickViewIds(R.id.rivDelete);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                String picPath = picList.get(position).getPicPath();
                int i = picPathList.indexOf(picPath);
                if (i != -1) {
                    picPathList.remove(i);
                    mAdapter.removeAt(i);
                }
                if (!hasAddButton) {
                    showAddButton();
                }
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvContentNum.setText(s.toString().length() + "/72");
            }
        });
        tvFunctionX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = etContent.getText().toString().trim();
                if (content.length() < 10) {
                    showToast("至少输入10个字");
                    return;
                }
                for (int i = 0; i < picPathList.size(); i++) {
                    pathData.append(picPathList.get(i));
                    if (i != (picPathList.size() - 1)) {
                        pathData.append(",");
                    }
                }
                mPresenter.report(otherID, reportType, content, pathData.toString());
            }
        });
        showAddButton();
    }

    private void showAddButton() {
        ReportPicBean reportPicBean = new ReportPicBean();
        reportPicBean.setPlaceholder(true);
        mAdapter.addData(reportPicBean);
        hasAddButton = true;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_report;
    }

    @Override
    public ReportPresenter setPresenter() {
        return new ReportPresenter(this);
    }

    @Override
    public void reportSuccess() {
        showToast("提交成功");
        finish();
    }

    @Override
    public void reportFailed() {

    }

    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (data != null) {
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : localMedia) {
                        String path = media.getPath();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            path = PathUtils.getPath(ReportActivity.this, Uri.parse(path));
                        }
                        aliUploadUtils.upLoadFile(path, new FileUploadCallback() {
                            @Override
                            public void onFailure(String str) {
                                showToast(str);
                            }

                            @Override
                            public void onSuccess(Object paramRequestString, String filePath) {
                                picPathList.add(filePath);
                                ReportPicBean reportPicBean = new ReportPicBean();
                                reportPicBean.setPicPath(filePath);
                                if (picPathList.size() == 5) {
                                    mAdapter.removeAt(4);
                                    mAdapter.addData(reportPicBean);
                                    hasAddButton = false;
                                } else {
                                    mAdapter.addData(picPathList.size() - 1, reportPicBean);
                                }

                            }

                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                            }
                        });
                    }
                }
            }
        }
    }
}
